package cn.tannn.ops.customer.dao;


import cn.tannn.jdevelops.jpa.repository.JpaBasicsRepository;
import cn.tannn.ops.customer.entity.RoleCustomer;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * 角色-系统用户
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2023/12/4 13:05
 */
public interface RoleCustomerDao extends JpaBasicsRepository<RoleCustomer,Long> {

    /**
     * 查询角色用户
     * @param userId userId
     * @param roleCode roleCode
     * @return RoleUser
     */
    Optional<RoleCustomer> findByUserIdAndRoleCode(Long userId, String roleCode);


    /**
     * 获取userId
     * @param roleCode 角色编号
     * @return userId
     */
    @Query("SELECT ru.userId FROM RoleCustomer ru where ru.roleCode = ?1 ")
    List<Long> findUserIdByRoleCode(String roleCode);

    /**
     * 获取userId
     * @param roleCode 角色编号
     * @return userId
     */
    @Query("SELECT ru.userId FROM RoleCustomer ru where ru.roleCode in (?1)  ")
    List<Long> findUserIdByRoleCodeIn(List<String>  roleCode);

    /**
     *  删除数据
     *
     * @param roleCode 角色
     * @param userIds 用户
     * @author tan
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    void deleteByRoleCodeAndUserIdIn(String roleCode, Collection<Long> userIds);

    /**
     *  删除数据
     *
     * @param roleCode 角色编号
     * @author tan
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    void deleteByRoleCodeIn(List<String> roleCode);


    /**
     * 查询角色编号集合
     *
     * @param userId 用户序号
     * @return roleCode
     * @author tan
     */
    @Query("SELECT ru.roleCode FROM RoleCustomer ru where ru.userId = ?1 ")
    List<String> findRoleCodeByUserId(Long userId);
}
